#!/bin/bash
# Go2 机器人网络配置脚本 - 自动化版本
# 支持参数: -y (自动确认) -i <接口名> (强制指定网口)
# 严格限制：只接受 en* 或 eth* 开头的网口

set -e

# ==================== 参数解析 ====================
AUTO_CONFIRM=false
FORCE_INTERFACE=""

while getopts "yi:" opt; do
    case $opt in
        y)
            AUTO_CONFIRM=true
            ;;
        i)
            FORCE_INTERFACE="$OPTARG"
            ;;
        \?)
            echo "用法: $0 [-y] [-i 接口名]"
            echo "  -y: 自动确认所有提示"
            echo "  -i: 强制使用指定网口（必须是en*或eth*）"
            exit 1
            ;;
    esac
done

# ==================== 颜色定义 ====================
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
NC='\033[0;9m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否以 root 权限运行
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "此脚本需要 root 权限，请使用 sudo 运行"
        exit 1
    fi
}

# 显示横幅
show_banner() {
    echo "=========================================="
    echo "   Go2 机器人网络配置脚本"
    echo "=========================================="
    echo
}

# 辅助函数：自动应答
ask_confirm() {
    local prompt="$1"
    local default="$2"
    
    if [[ "$AUTO_CONFIRM" == "true" ]]; then
        echo "$default"
        return 0
    fi
    
    read -p "$prompt" response
    echo "${response:-$default}"
}

# 严格查找 en 或 eth 开头的网口
find_lingxin_interface() {
    # 如果强制指定了网口，验证格式
    if [[ -n "$FORCE_INTERFACE" ]]; then
        if [[ ! "$FORCE_INTERFACE" =~ ^(en|eth) ]]; then
            log_error "指定的接口 $FORCE_INTERFACE 不是 en* 或 eth* 格式，拒绝配置"
            log_error "允许的接口格式: enx*, eth*"
            exit 1
        fi
        TARGET_INTERFACE="$FORCE_INTERFACE"
        log_success "强制使用指定网口: $TARGET_INTERFACE"
        return 0
    fi
    
    log_info "扫描网络接口（仅查找 en*, eth*）..."
    
    # 只查找 enx, eth 开头的网口
    en_interfaces=$(ip link show | grep -E "^[0-9]+:" | grep -E "\b(e(nx?|th))[0-9]" | awk -F: '{print $2}' | tr -d ' ' | sed '/^$/d')
    
    if [[ -n "$en_interfaces" ]]; then
        log_success "找到可用网口:"
        echo "$en_interfaces" | while read iface; do
            echo "  - $iface"
        done
        
        # 如果有多个，优先选择 enx 开头的
        enx_iface=$(echo "$en_interfaces" | grep "^enx" | head -n1)
        if [[ -n "$enx_iface" ]]; then
            TARGET_INTERFACE="$enx_iface"
        else
            TARGET_INTERFACE=$(echo "$en_interfaces" | head -n1)
        fi
        log_success "自动选择: $TARGET_INTERFACE"
        return 0
    fi
    
    log_error "未找到任何 en* 或 eth* 开头的可用网络接口"
    log_error "已过滤掉的接口: usb0, wlan0, lo, virbr*, docker*"
    log_error "请检查硬件连接或手动指定接口"
    exit 1
}

# 详细分析网口状态
analyze_interface_status() {
    local interface=$1
    log_info "分析网口 $interface 的状态..."
    
    local interface_info=$(ip link show "$interface")
    local state=$(echo "$interface_info" | grep -o "state [A-Z]*" | cut -d' ' -f2)
    local flags=$(echo "$interface_info" | grep -o "<.*>" | tr -d '<>')
    local ip_info=$(ip addr show "$interface" | grep "inet " | head -1)
    
    echo
    echo "--- 网口状态分析 ($interface) ---"
    
    if [[ -n "$ip_info" ]]; then
        log_info "当前IP配置: $ip_info"
    else
        log_warning "当前IP配置: 未配置IP地址"
    fi
    
    if echo "$flags" | grep -q "NO-CARRIER"; then
        log_warning "⚠️  物理连接: NO-CARRIER (未检测到载波信号)"
        echo "   可能原因:"
        echo "   • 网线未连接到 Go2 机器人"
        echo "   • Go2 机器人未开机"
    else
        log_success "✅ 物理连接: 检测到载波信号"
    fi
    
    if echo "$flags" | grep -q "LOWER_UP"; then
        log_success "✅ 链路状态: LOWER_UP (链路已建立)"
    else
        log_warning "⚠️  链路状态: 未建立"
    fi
    
    if [[ "$state" == "UP" ]]; then
        log_success "✅ 接口状态: UP (已启用)"
    else
        log_warning "⚠️  接口状态: $state (未启用)"
    fi
    
    echo "----------------------------------------"
    echo
}

# 检查物理连接
check_physical_connection() {
    log_info "检查 $TARGET_INTERFACE 物理连接..."
    
    if command -v ethtool &>/dev/null; then
        link_status=$(ethtool "$TARGET_INTERFACE" 2>/dev/null | grep "Link detected" | cut -d: -f2 | tr -d ' ' || echo "unknown")
        if [[ "$link_status" == "yes" ]]; then
            log_success "物理连接: 检测到链路"
            return 0
        elif [[ "$link_status" == "no" ]]; then
            log_warning "物理连接: 未检测到链路"
            echo
            local continue_setup=$(ask_confirm "是否继续配置? (y/n, 默认 y): " "y")
            if [[ $continue_setup != "y" && $continue_setup != "Y" ]]; then
                log_info "用户取消操作"
                exit 0
            fi
        fi
    else
        log_warning "未安装 ethtool，跳过详细检查"
    fi
}

# ==================== 新增：清理旧配置函数 ====================

# 清理所有旧的 Go2 配置
cleanup_old_go2_config() {
    log_info "清理旧的 Go2 机器人网络配置..."
    
    if [[ ! -f "/etc/network/interfaces" ]]; then
        log_warning "配置文件不存在，跳过清理"
        return
    fi
    
    # 备份原始配置（只备份一次）
    if [[ -z "$CONFIG_BACKUP" ]]; then
        CONFIG_BACKUP="/etc/network/interfaces.backup.$(date +%Y%m%d_%H%M%S)"
        cp /etc/network/interfaces "$CONFIG_BACKUP"
        log_success "已备份配置文件: $CONFIG_BACKUP"
    fi
    
    # 删除所有包含 "Go2 机器人网络配置" 的配置块
    # 匹配注释行及其后续4行配置（auto, iface, address, netmask）
    sed -i '/# Go2 机器人网络配置/,+4d' /etc/network/interfaces
    
    # 清理可能残留的多余空行（最多保留一个空行）
    sed -i ':a; /^$/N; s/\n\n/\n/; ta' /etc/network/interfaces
    sed -i '$ { /^$/d; }' /etc/network/interfaces
    
    log_success "已清理旧的 Go2 配置"
}

# ==================== 修改：配置函数 ====================

# 配置静态 IP（自动清理旧配置后再添加）
configure_static_ip() {
    local interface=$1
    local ip_address="192.168.123.222"
    
    # === 核心：先清理旧配置 ===
    cleanup_old_go2_config
    
    log_info "配置静态 IP: $ip_address 到接口 $interface"
    
    # 在文件末尾添加新配置
    cat >> /etc/network/interfaces << EOF

# Go2 机器人网络配置 (自动添加 - $(date) - 接口: $interface)
auto $interface
iface $interface inet static
    address $ip_address
    netmask 255.255.255.0

EOF

    log_success "✅ 已添加/更新网络配置"
    echo "----------------------------------------"
    tail -6 /etc/network/interfaces
    echo "----------------------------------------"
}


# 重启网络服务
restart_network() {
    log_info "重启网络服务..."
    
    ifdown "$TARGET_INTERFACE" 2>/dev/null || true
    if ifup "$TARGET_INTERFACE"; then
        log_success "网络接口启动成功"
    else
        log_error "启动失败，尝试手动配置"
        ip addr flush dev "$TARGET_INTERFACE" 2>/dev/null || true
        ip addr add 192.168.123.222/24 dev "$TARGET_INTERFACE" 2>/dev/null || true
        ip link set "$TARGET_INTERFACE" up
        log_warning "已使用手动配置"
    fi
    
    sleep 3
}

# 验证配置
verify_configuration() {
    log_info "验证网络配置..."
    
    current_ip=$(ip addr show "$TARGET_INTERFACE" | grep "inet " | awk '{print $2}' | cut -d/ -f1 | head -n1)
    if [[ "$current_ip" == "192.168.123.222" ]]; then
        log_success "IP 地址配置正确: $current_ip"
    else
        log_error "IP 配置失败，当前 IP: $current_ip"
        return 1
    fi
    
    return 0
}

# 测试连接
test_connection() {
    local target_ip="192.168.123.161"
    
    log_info "测试连接到 Go2 机器人: $target_ip"
    echo
    
    # 检查是否可以 ping
    if ! command -v ping &>/dev/null; then
        log_error "未安装 ping 命令"
        return 1
    fi
    
    log_info "开始 ping 测试..."
    if sudo ping -c 4 -W 3 "$target_ip" 2>/dev/null | grep -q "64 bytes"; then
        log_success "🎉 连接测试成功！"
        sudo ping -c 2 -W 2 "$target_ip" | head -4
        return 0
    else
        log_error "连接测试失败"
        echo
        log_warning "可能原因:"
        echo "  1. Go2 机器人未开机"
        echo "  2. 网线连接异常"
        echo "  3. IP 配置错误"
        return 1
    fi
}

# 显示摘要
show_summary() {
    echo
    echo "=========================================="
    echo "           配置完成摘要"
    echo "=========================================="
    echo "🔌 网络接口: $TARGET_INTERFACE"
    echo "📍 本地 IP: 192.168.123.222"
    echo "🎯 目标设备: 192.168.123.161"
    echo "📁 配置文件: /etc/network/interfaces"
    
    if [[ -f "$backup_file" ]]; then
        echo "💾 配置备份: $backup_file"
    fi
    
    echo
    log_success "配置完成！"
    echo
    log_info "常用命令:"
    echo "   测试连接: sudo ping 192.168.123.161"
    echo "   接口状态: ip addr show $TARGET_INTERFACE"
    echo "   查看配置: cat /etc/network/interfaces"
    echo
}

# ==================== 主函数 ====================

main() {
    show_banner
    check_root
    
    log_info "当前网络接口状态:"
    ip addr | grep -E "^[0-9]+:|state|inet" | head -20
    
    echo
    find_lingxin_interface
    analyze_interface_status "$TARGET_INTERFACE"
    check_physical_connection
    
    log_info "当前网络配置预览:"
    echo "=========================================="
    cat /etc/network/interfaces
    echo "=========================================="
    
    local confirm=$(ask_confirm "是否继续? (y/n, 默认 y): " "y")
    if [[ $confirm != "y" && $confirm != "Y" ]]; then
        log_info "用户取消操作"
        exit 0
    fi
    
    configure_static_ip "$TARGET_INTERFACE"  # 调用新函数
    restart_network
    verify_configuration
    test_connection
    show_summary
}

main "$@"